const Joi = require("joi");
const response = require("../utils/response");
const dayjs = require("dayjs");
// 统一处理数据库错误
const handleDatabaseError = (ctx, err, msg) => {
  if (err.code === 11000) {
    response.error(ctx, { message: err.message || msg });
  } else {
    response.error(ctx, { message: err.message || msg });
  }
};
const dealNotEmpty = (tip) => {
  return Joi.string()
    .min(1)
    .required()
    .messages({
      "string.empty": tip + "不能为空",
      "any.required": tip + "是必需的",
    });
};
const dealNotEmptyArry = (tip) => {
  return Joi.array()
    .min(1)
    .required()
    .messages({
      "array.base": tip + "未选择（notarry）",
      "array.min": tip + "未选择（null）",
      "any.required": "请选择" + tip,
    });
};
const paginate = (model, query, params, populateFields = []) => {
  return new Promise(async (resolve, reject) => {
    let pageSize = parseInt(params.pageSize) || 10; // 每页显示的记录数
    let currentPage = parseInt(params.currentPage) || 1; // 当前页码
    let skip = (currentPage - 1) * pageSize; // 跳过的记录数
    let isAll = params.isAll || false; // 跳过的记录数
    try {
      let queryBuilder = isAll ? model.find(query) : model.find(query).skip(skip).limit(pageSize);
      populateFields.forEach((field) => {
        queryBuilder = queryBuilder.populate(populateFields);
      });

      let results = await queryBuilder.exec();
      let total = await model.find(query).countDocuments();

      resolve({
        results,
        total,
      });
    } catch (err) {
      throw err;
    }
  });
};
const buildRangeQuery = (start, end, IsTime) => {
  if (start || end) {
    let rangeQuery = {};
    if (start) rangeQuery.$gte = IsTime ? dayjs(start).valueOf() : +start;
    if (end) rangeQuery.$lte = IsTime ? dayjs(end).valueOf() : +end;
    return rangeQuery;
  }
  return undefined;
};

module.exports = {
  buildRangeQuery,
  handleDatabaseError,
  dealNotEmpty,
  dealNotEmptyArry,
  paginate,
};
